package com.itheima.health.controller.backend;

import com.itheima.health.constant.MessageConstant;
import com.itheima.health.constant.RedisMessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.utils.MsgUtil;
import com.itheima.health.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @package：com.itheima.health.controller.backend
 * @Author: luoll
 * @Date: 2024/7/14 15:09
 */
@RestController
public class ValidateCode {
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/validatecode/backendSend4Login.do")
    public Result backendSend4Login(String telephone) {
        // 1.生成4位数字验证码
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        //2.发送短信
//         String isOk = SMSUtils.sendTelephoneLoginNotice(telephone, authCode);
        String isOk = MsgUtil.sendCode(telephone, String.valueOf(code));
//        String isOk = "OK"; // 模拟短信发送成功
        System.out.println("后台手机快速登录发送手机验证码: " + isOk);
        System.out.println("验证码为: " + code);
        // 3.判断短信是否发送成功? 是否为OK
        if ("OK".equals(isOk)) {
            // 3.1.短信发送成功，把验证码放到Redis中,存活时间5分钟
//            ValueOperations<String, Object> ops = redisTemplate.opsForValue();
//            ops.set(telephone + RedisMessageConstant.SENDTYPE_BACKEND_GETPWD, code, 5, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set(telephone+RedisMessageConstant.SENDTYPE_BACKEND_GETPWD,code.toString(),5, TimeUnit.MINUTES);

            // 3.2.返回统一响应结果，Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } else {
            // 3.3.短信发送失败，返回统一响应结果，Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
}